package demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 第二个Socket服务端 用于接收客户端发过来的文件转发给服务端
 * 
 * @author sundy.hu
 * 
 * @version 1.0
 * 
 * @date 2012-11-28
 * 
 */
public class Server2 implements Runnable {

	// Socket服务器地址
	private String address;
	// Socket服务器地址
	private int port;
	// 本SocketServer端口
	private int server_port;

	private byte[] data;

	public Server2(String address, int port, int server_port) {
		this.address = address;
		this.port = port;
		this.server_port = server_port;
	}

	@Override
	public void run() {

		try {
			ServerSocket serverSocket = new ServerSocket(server_port);
			System.out.println("proxy server startup at port " + server_port);
			while (true) {
				Socket client = serverSocket.accept();
				data = receiver(client);
				Socket client2 = new Socket(address, port);
				send(client2, data);
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	// 接收文件
	private byte[] receiver(Socket client) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			if (null != client) {
				BufferedInputStream input = new BufferedInputStream(
						client.getInputStream());
				DataInputStream dis = new DataInputStream(input) ;
				
				int len = 0;
				while ((len = dis.read()) != -1) {
					bos.write(len);
				}
				input.close();
				client.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return bos.toByteArray();
	}

	// 发送文件给Socket服务端
	private void send(Socket client, byte[] data) {
		try {
			if (null != client) {
				BufferedOutputStream output = new BufferedOutputStream(
						client.getOutputStream());
				DataOutputStream dos = new DataOutputStream(output) ;
				dos.write(data);
				dos.flush();
				dos.close();
				output.flush() ;
				output.close() ;
				client.close();
				System.out.println("files send successful");
			}
		} catch (IOException ex) {
			System.out.println("client not connected server");
			ex.printStackTrace();
		}
	}

}
